package com.sgb.kjwl.view.ui.activity.transport;

import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;

import androidx.databinding.DataBindingUtil;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityLocationAddressSelectionBinding;
import com.sgb.kjwl.model.entity.transport.AMapAddressEntity;
import com.sgb.kjwl.utils.AddressHelper;
import com.sgb.kjwl.view.constant.RouterKey;

import com.sgb.link.router.PathTransport;

import com.swgk.core.util.MLog;

import java.util.ArrayList;
import java.util.List;

/**
 * Describe:    选择地址
 * Author:  yangLei
 * Date:    2021/7/28
 */
@Route(path = PathTransport.LocationSelectionActivity)
public class LocationSelectionActivity extends AppActivity implements PoiSearch.OnPoiSearchListener {
    @Autowired(name = RouterKey.STRING, desc = "mCurrCity")
    public String mCurrCity;
    @Autowired(name = RouterKey.INT, desc = "type")
    public int type = 0;
    //地图搜索Poi类型
    private final static String POI_TYPE = "汽车服务|汽车销售|汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|" +
            "体育休闲服务|医疗保健服务|住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|" +
            "金融保险服务|公司企业|道路附属设施|公共设施";
    //搜索返回的地址数目
    private final int limit = 10;
    //搜索扩展字段 base表示只返回基础数据，all表示所有数据 ，默认 base
    private final String extensions = "all";
    //地址列表
    private List<AMapAddressEntity> mList = new ArrayList<>();
    //当前选中城市的POI信息
    private AMapAddressEntity selectEntity;

    private boolean IsViewCitySelector = false;
    private ActivityLocationAddressSelectionBinding mBinding;


    @Override
    protected void initView() {
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_location_address_selection);
    }

    @Override
    protected void init() {
        ARouter.getInstance().inject(LocationSelectionActivity.this);
        mBinding.ivBack.setOnClickListener(view -> finish());
        initEvents();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (TextUtils.isEmpty(mCurrCity)) {
            mCurrCity = "乌鲁木齐";
        }
        mBinding.citySelectView.setCurrCity(mCurrCity);
    }

    private void initEvents() {

        mBinding.citySelectView.setCheckedClickListener(name -> checkedCityResult(name));
        mBinding.cetCity.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String keyWords = s.toString();
                mBinding.citySelectView.filterData(keyWords);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    /**
     * 选中城市
     *
     * @param entity
     */
    private void checkedCityResult(AMapAddressEntity entity) {
        if (!TextUtils.isEmpty(entity.getCity())) {
            searchByCityAndKeyword(entity.getCity());
        }
    }

    /**
     * 通过城市和关键字搜索地区
     */
    public void searchByCityAndKeyword(String cityName) {
        //设置当前城市
        PoiSearch.Query query = new PoiSearch.Query("", POI_TYPE, cityName);
        query.setPageSize(limit);
        query.setPageNum(1);
        query.setExtensions(extensions);
        query.setCityLimit(true);
        PoiSearch poiSearch = new PoiSearch(this, query);
        poiSearch.setOnPoiSearchListener(this);
        poiSearch.searchPOIAsyn();
    }

    @Override
    public void onPoiSearched(PoiResult poiResult, int code) {
        if (code != 1000) {
            MLog.d("debug", "搜索失败");
            return;
        }
        //1000 成功
        mList.clear();
        //添加地址信息
        List<PoiItem> poiList = poiResult.getPois();
        if (poiList != null && poiList.size() > 0) {
            PoiItem poi = poiList.get(0);
            selectEntity = new AMapAddressEntity(poi.getProvinceName(), poi.getCityName(), poi.getAdName(),
                    poi.getSnippet(), poi.getTitle(), "0",
                    poi.getLatLonPoint().getLatitude(), poi.getLatLonPoint().getLongitude(),
                    poi.getProvinceCode(), poi.getCityCode(), poi.getAdCode());
            AddressHelper.getInstance().findCode(selectEntity);
            Intent intent = new Intent();
            intent.putExtra(RouterKey.DATA, selectEntity);
            intent.putExtra(RouterKey.INT, type);
            setResult(200, intent);
            finish();
        } else {
            MLog.d("debug", "没有搜到，请尝试其他关键词");
        }
    }


    @Override
    public void onPoiItemSearched(PoiItem poiItem, int code) {

    }
}
